package org.example.route.service.impl;



import org.example.route.mapper.CityMapper;
import org.example.route.mapper.ProvinceMapper;
import org.example.route.model.dto.BaseRequest;
import org.example.route.model.dto.ProvinceDTO;
import org.example.route.model.dto.ProvinceQueryDTO;
import org.example.route.model.pojo.City;
import org.example.route.model.pojo.Province;
import org.example.route.model.vo.ProvinceVO;
import org.example.route.service.ProvinceService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ProvinceServiceImpl implements ProvinceService {
    @Autowired
    private ProvinceMapper provinceMapper;
    @Autowired
    private CityMapper cityMapper;


    @Tool(name = "listProvince", description = "查询并获取省份的信息，包括省份名称等")
    public List<ProvinceVO> list(@ToolParam(description = "省份模糊查询的名称，比如安徽、安等") String name) {
        ProvinceQueryDTO provinceQueryDTO = new ProvinceQueryDTO(name);
        return list(provinceQueryDTO);

    }




    @Override
    public List<ProvinceVO> list(ProvinceQueryDTO provinceQueryDTO) {
        List <Province> provinceList = provinceMapper.list(provinceQueryDTO);
        List<ProvinceVO> provinceVOList = new ArrayList<>();
        for (Province province : provinceList) {
            ProvinceVO provinceVO = new ProvinceVO(province.getId(), province.getName());
            provinceVOList.add(provinceVO);
        }
        return provinceVOList;
    }

    @Override
    public void add(ProvinceDTO provinceDTO) {
        Province province = Province.builder()
                .name(provinceDTO.getName())
                .build();

        provinceMapper.add(province);
    }

    @Override
    public void delete(BaseRequest baseRequest) {
        Province province = provinceMapper.getById(Long.parseLong(baseRequest.getKey()));
        if (Objects.isNull(province))
        {
            throw new RuntimeException("省份不存在");
        }

        List<City> cities = cityMapper.getByProvinceId(province.getId());
        if (!cities.isEmpty())
        {
            throw new RuntimeException("省份下有城市，不能删除");
        }

        provinceMapper.deleteById(province.getId());

    }
}
